package com.showsu.editor.utils.remote;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.platform.xhs.AwemeDetailPlatformResult;
import com.showsu.editor.entity.platform.xhs.XhsAwemeDetailResult;
import com.showsu.editor.entity.remote.VideoDetailResult;
import com.showsu.editor.entity.remote.WhoseCardVideoDetailResp;
import com.showsu.editor.entity.remote.moreapi.DyAwemeDetailResult;
import com.showsu.editor.entity.remote.r52.R52XhsAwemeDetailResult;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.Constant;
import com.showsu.editor.utils.GsonFailSafeArrayJsonDeserializer;
import com.showsu.editor.utils.RetryUtils;
import com.showsu.editor.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description: 52新版的接口工具，之前的详见R52Util.java，新的接口返回结构都变了，因此新起一个，便于未来可能的来回切换
 * 外部接口服务：https://apifox.com/apidoc/shared-8b412119-c090-4e01-80bb-5d15c871379a/api-141029112
 * @Date: Created in 18:00 下午 2024/1/25
 * @Modified By:
 */
@Slf4j
@Component
public class NewR52Util {

    @Value("${r52API.url}")
    private String r52Url;

    @Value("${r52API.token}")
    private String r52Token;

    /**
     * 最大重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;
    
    private static final int timeout = 10000;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 2000;

    /**
     * gson反序列化时，用于忽略array的错误。因为有的时候字段返回为空，我们认为是可以接受的。
     */
    private GsonFailSafeArrayJsonDeserializer gsonFailSafeArrayJsonDeserializer = new GsonFailSafeArrayJsonDeserializer();

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 获取dy作品详情
     * https://apifox.com/apidoc/shared-8b412119-c090-4e01-80bb-5d15c871379a/api-143394828
     * @param awemeId 作品id
     * @return
     */
    public WhoseCardVideoDetailResp getDyAwemeDetail(String awemeId, Long interfaceId) {
        if (StringUtils.isBlank(awemeId)) {
            return null;
        }
        WhoseCardVideoDetailResp finalResult = new WhoseCardVideoDetailResp();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(r52Url).append("/dy/aweme_detail?token=").append(r52Token)
                            .append("&aweme_id=").append(awemeId);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("NewR52Util查询dy作品详情-响应耗时:{}-awemeId:{}", System.currentTimeMillis() - start, awemeId);
                    DyAwemeDetailResult temp = JSON.parseObject(responseInner, DyAwemeDetailResult.class);
                    if (temp == null || temp.getData() == null || temp.getData().getAweme_detail() == null
                            || (temp != null && temp.getCode() != null && temp.getCode().intValue() != 200)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("NewR52Util.getDyAwemeDetail(String,String) error, awemeId:{}, e:{}", awemeId, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("awemeId=").append(awemeId).toString());
            return finalResult;
        }
        try {
            DyAwemeDetailResult awemeResult = JSON.parseObject(response, DyAwemeDetailResult.class);
            if (awemeResult != null && awemeResult.getData() != null && awemeResult.getData().getAweme_detail() != null) {
                VideoDetailResult videoDetailResult = new VideoDetailResult();
                videoDetailResult.setAweme_detail(awemeResult.getData().getAweme_detail());
                finalResult.setResult(videoDetailResult);
            } else {
                log.info("NewR52Util.getDyAwemeDetail(String) awemeResult is null, awemeId:{}", awemeId);
            }
        } catch (Exception e) {
            log.error("NewR52Util.getDyAwemeDetail(String,String) convert error, awemeId:{}, e:{}", awemeId, e);
        }
        return finalResult;
    }


        /**
         * 查询xhs笔记详情
         * https://apifox.com/apidoc/shared-8b412119-c090-4e01-80bb-5d15c871379a/api-141029112
         * @param noteId
         * @return
         */
    public XhsAwemeDetailResult getXhsAwemeDetail(String noteId, String xSecToken, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        //返回对象
        XhsAwemeDetailResult result = new XhsAwemeDetailResult();

        Type type = new TypeToken<R52XhsAwemeDetailResult>(){}.getType();
        Gson gson = new GsonBuilder().registerTypeAdapter(List.class, gsonFailSafeArrayJsonDeserializer).create();

        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(r52Url).append("/xhs/note_info?token=").append(r52Token)
                            .append("&note_id=").append(noteId).append("&xsec_token=").append(xSecToken);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("NewR52Util查询xhs作品详情-响应耗时:{}-noteId:{}", System.currentTimeMillis() - start, noteId);
                    R52XhsAwemeDetailResult temp = gson.fromJson(responseInner, type);
                    if (temp != null
                            && (Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getMsg()))
                                || (temp.getData() != null && Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getData().getMsg())))
                            )
                    ) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                        return Constant.xhsAwemeNotExist1;
                    }

                    //如果平台那边报错再重试一次
                    if (temp == null || temp.getData() == null
                            || (temp != null && temp.getCode() != null && temp.getCode().intValue() != 200)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("NewR52Util.getXhsAwemeDetail(String) error, noteId:{}, e:{}", noteId, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("noteId=").append(noteId).toString());
            return result;
        }
        if (response.equals(Constant.xhsAwemeNotExist1)) {
            return null;
        }
        try {
            R52XhsAwemeDetailResult r52XhsAwemeDetailResult = gson.fromJson(response, type);
            if (r52XhsAwemeDetailResult != null && r52XhsAwemeDetailResult.getData() != null
                    && StringUtils.isNotBlank(r52XhsAwemeDetailResult.getData().getMsg())
                    && Constant.containsXhsAwemeNotExistHint(r52XhsAwemeDetailResult.getData().getMsg())) {
                return null;
            }
            if (r52XhsAwemeDetailResult != null && r52XhsAwemeDetailResult.getData() != null
                    && !CollectionUtils.isEmpty(r52XhsAwemeDetailResult.getData().getItems())
                    && r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card() != null) {
                result.setCode(r52XhsAwemeDetailResult.getCode());

                AwemeDetailPlatformResult awemeDetailPlatformResult = new AwemeDetailPlatformResult();
                result.setData(awemeDetailPlatformResult);
                List<AwemeDetailPlatformResult.AwemeDetail> awemeDetailList = new ArrayList<>();
                awemeDetailPlatformResult.setData(awemeDetailList);
                AwemeDetailPlatformResult.AwemeDetail awemeDetail = awemeDetailPlatformResult.new AwemeDetail();
                awemeDetailList.add(awemeDetail);
                AwemeDetailPlatformResult.AwemeDetail.User user = awemeDetail.new User();
                awemeDetail.setUser(user);
                List<AwemeDetailPlatformResult.AwemeDetail.Note> noteList = new ArrayList<>();
                AwemeDetailPlatformResult.AwemeDetail.Note note = awemeDetail.new Note();
                noteList.add(note);
                awemeDetail.setNote_list(noteList);

                if (r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getUser() != null) {
                    user.setUserid(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getUser().getUser_id());
                    user.setNickname(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getUser().getNickname());
                    user.setImage(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getUser().getAvatar());
                }

                if (r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getInteract_info() != null) {
                    note.setLiked_count(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getInteract_info().getLiked_count());
                    note.setCollected(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getInteract_info().getCollected());
                    note.setCollected_count(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getInteract_info().getCollected_count());
                    note.setComments_count(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getInteract_info().getComment_count());
                    note.setShared_count(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getInteract_info().getShare_count());
                }

                AwemeDetailPlatformResult.AwemeDetail.Note.ShareInfo shareInfo = note.new ShareInfo();
                note.setShare_info(shareInfo);

                //笔记文案
                if (StringUtils.isNotBlank(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getTitle())) {
                    shareInfo.setTitle(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getTitle());
                }

                if (! CollectionUtils.isEmpty(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getImage_list())) {
                    List<AwemeDetailPlatformResult.AwemeDetail.Note.Image> imageList = new ArrayList<>();
                    note.setImages_list(imageList);
                    for (R52XhsAwemeDetailResult.R52XhsAwemeDetailData.Item.Note.Cover cover : r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getImage_list()) {
                        AwemeDetailPlatformResult.AwemeDetail.Note.Image image = note.new Image();
                        image.setFileid(cover.getFileid());
                        image.setHeight(cover.getHeight());
                        image.setWidth(cover.getWidth());
                        image.setUrl(cover.getUrl_default());
                        image.setOriginal(cover.getUrl_default());
                        if(cover.getStream() != null && !CollectionUtils.isEmpty(cover.getStream().getH264())){
                            AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto livePhoto = image.new LivePhoto();
                            AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media media = livePhoto.new Media();
                            AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media.Stream stream = media.new Stream();
                            List<AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media.Stream.H264> h264List = new ArrayList<>();
                            for (R52XhsAwemeDetailResult.R52XhsAwemeDetailData.Item.Note.Cover.Stream.H264 h264 : cover.getStream().getH264()) {
                                AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media.Stream.H264 h264_1 = stream.new H264();
                                h264_1.setMaster_url(h264.getMaster_url());
                                h264List.add(h264_1);
                            }
                            stream.setH264(h264List);
                            media.setStream(stream);
                            livePhoto.setMedia(media);
                            image.setLive_photo(livePhoto);
                        }
                        imageList.add(image);
                    }
                    shareInfo.setImage(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getImage_list().get(0).getUrl_default());
                }

                note.setTime(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getTime());
                note.setTitle(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getTitle());
                note.setLast_update_time(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getLast_update_time());
                note.setType(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getType());
                note.setDesc(r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getDesc());
                List<AwemeDetailPlatformResult.AwemeDetail.Note.HashTagDTO> hashTagDTOList=new ArrayList<>();
                for(R52XhsAwemeDetailResult.R52XhsAwemeDetailData.Item.Note.Tag tag : r52XhsAwemeDetailResult.getData().getItems().get(0).getNote_card().getTag_list()){
                    AwemeDetailPlatformResult.AwemeDetail.Note.HashTagDTO hashTag= new AwemeDetailPlatformResult().new AwemeDetail().new Note().new HashTagDTO();
                    hashTag.setId(tag.getId());
                    hashTag.setName(tag.getName());
                    hashTagDTOList.add(hashTag);
                }
                note.setHash_tag(hashTagDTOList);
            }
        } catch (Exception e) {
            log.error("NewR52Util.getXhsAwemeDetail(String) convert error, noteId:{}, e:{}", noteId, e);
        }
        return result;
    }

    public static void main(String[] args) {
        //String response = HttpUtil.get("https://api.linkupapi.top/dy/video_play_count?token=uzmuLejXgSEU93Lg&aweme_id=7341404935281593626");
        //String response = HttpUtil.get("https://api.linkupapi.top/dy/user_info_v2?token=uzmuLejXgSEU93Lg&sec_user_id=MS4wLjABAAAAuTvWJbXr0rUGkB6LPyFKRizfonJozTrPY0ZE3rnaZq8VnuUXiGJYIOd9i52eJa55");
        String response = HttpUtil.get("https://api.linkupapi.top/xhs/note_info?token=uzmuLejXgSEU93Lg&note_id=66b479c8000000001e01e1ae");
        //String response = HttpUtil.get("https://api.linkupapi.top//xhs/user_notes?token=uzmuLejXgSEU93Lg&user_id=5cfbc3f10000000018023ebb&cursor=");

        System.out.println(response);
    }
}
